<template>
  <div class="home">
    <section class="my_header">
      <section @click = "gotoback()" class="left">
        <i class="icon_style iconfont icon-arrowleft"></i>
        <button class="back">返回</button>
      </section>
    </section>

    <section class="center">
      <section class="center_header">
        <section class="center_header_left">
          <img :src="$store.state.baseImgUrl+$store.state.articleDetail.authorAvatar" alt="" class="avatar">
        </section>
        <section class="center_header_center">
          <p><span class="nick">{{$store.state.articleDetail.authorNick}}</span></p>
          <p><span class="datetime">{{$store.state.articleDetail.createTime | time}}</span></p>
        </section>
      </section>
      <div id="editor" ref="editor" style="height: 100%"></div>
    </section>

    <section class="btn_nav">
      <section class="btn_nav_item">
        <i class="icon_style iconfont icon-zan"
           :class="{'icon_style_active':this.$store.state.articleDetail.upvote}"
           @click="upvote()">点赞：</i>
        <span :class="{'is_selected':this.$store.state.articleDetail.upvote}">{{this.$store.state.articleDetail.upvoteCount}}</span>
      </section>
      <section class="btn_nav_item">
        <i class="icon_style iconfont icon-jushoucang"
           :class="{'icon_style_active':this.$store.state.articleDetail.like}"
           @click="like()">收藏：</i>
        <span :class="{'is_selected':this.$store.state.articleDetail.like}">{{this.$store.state.articleDetail.likeCount}}</span>
      </section>
    </section>

    <section class="comment">
      <ul class="post_list_ul" v-infinite-scroll="loadMore"
          infinite-scroll-disabled="loading"
          infinite-scroll-distance="10">
        <li class="post_list_li" v-for="item in commentList" :key="item.id" >
          <section class="li_header">
            <section class="li_header_left">
              <img :src="$store.state.baseImgUrl+item.commentAvatar" alt="" class="avatar">
            </section>
            <section class="li_header_center">
              <span class="nick">{{item.commentNick}}</span>
            </section>
            <section class="li_header_right">
              <span class="datetime">{{item.createTime | time}}</span>
            </section>
            <button class="btn" @click="replyComment(item)">{{item.commentedCount}}回复</button>
          </section>

          <section class="li_center" @click="replyComment(item)">
            <section  class="li_center_container">
                <span class="container">
                  <p>{{item.content}}</p>
                </span>
            </section>
          </section>
        </li>

      </ul>
    </section>


    <section class="bottom_nav">
      <section class="content">
        <textarea  id="content_input" rows="1" placeholder="写评论..." style="" @keyup="autoResize()" v-model="content"></textarea>
        <button class="btn" @click="comment()">发布</button>
      </section>
    </section>

    <!--<jm-fooder></jm-fooder>-->

  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex'
  import JmFooder from '../../components/footer/Footer';
  import { Toast } from 'mint-ui'
  import Quill from 'quill'

  export default {
    data() {
      return {
        editor: null,
        commentList:[],
        offset: 0,
        content: "",
        loading: false,
        showLoading: true,
        preventRepeat: false,
      }
    },
    components:{
      JmFooder
    },
    mounted(){
      // 如果从详情返回并且之前存有对应的查询条件和参数
      // 则直接渲染之前的数据
      if (window.window.sessionStorage.commentList) {
        this.commentList = JSON.parse(window.window.sessionStorage.commentList);
        this.$nextTick(() => $(window).scrollTop(window.window.sessionStorage.scrollTop));
        this.offset = this.commentList.length;
        this.init();
      } else {
        this.init();
      }
    },
    beforeRouteLeave(to, from, next) {
      // 如果跳转到详情页面，则记录关键数据
      // 方便从详情页面返回到该页面的时候继续加载之前位置的数据
      if (to.path === '/comment') {
        // 当前滚动条位置
        window.window.sessionStorage.scrollTop = $(window).scrollTop();
        // 当前页面数据
        window.window.sessionStorage.commentList = JSON.stringify(this.commentList);
      }
      $(window).off('scroll');
      next();
    },
    beforeRouteEnter(to, from, next) {
      if (from.path !== '/comment') {
        // 页面切换移除之前记录的数据集
//        if (window.window.sessionStorage.scrollTop) {
          window.window.sessionStorage.removeItem('commentList');
//        }
      }
      next();
    },
    watch:{
    },
    computed: {
    },
    methods: {
      ...mapMutations([
        'UPDATE_LIKE',
        'UPDATE_UPVOTE',
        'SAVE_COMMENT'
      ]),
      init(){
        this.editor = new Quill('#editor', {
          theme: 'bubble'
        });
        this.$refs.editor.children[0].innerHTML = this.$store.state.articleDetail.content;
        this.editor.enable(false);
        if (typeof(this.$store.state.articleDetail) === "undefined" || this.$store.state.articleDetail === null){
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
            return;
          }, 2000);
          this.gotoback();
        }
      },

      gotoback(){
        this.$router.go(-1)
      },
      async loadMore(){
        console.log("load....");
        this.loading = true;

        //获取信息
        let res = null;
        let url = '/v1/comment?articleId=' + this.$store.state.articleDetail.id
          + '&start=' + this.offset
          + '&length=' + this.$store.state.length

        await this.axios.get(url)
          .then(response => {
            res = response.data;
          })

        if (res.success){

        }else{
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
            return;
          }, 2000);
        }
        this.offset += res.result.length;
        this.commentList = [...this.commentList, ...res.result];
        if (res.result.length > 0){
          this.loading = false;
        }

        if (res.result.length < this.$store.state.length) {
          this.showLoading = false;
          return;
        }
      },

      replyComment(item){
        let commentDetail = [];
        commentDetail.push(item);
        this.SAVE_COMMENT(commentDetail);
        this.preventRepeat = false;
        this.$router.push('/comment');
      },

      async comment(){
        //获取信息
        if (this.content === ""){
          let instance = Toast({message: '评论信息不能为空', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return ;
        }
        let res = null;
        let url = '/v1/comment'
          let param = {
            commentId: this.$store.state.userInfo.userId,
            commentNick: this.$store.state.userInfo.nick,
            commentAvatar: this.$store.state.userInfo.avatar,
            content: this.content,
            articleId: this.$store.state.articleDetail.id,
            commentParentId: 0,
            commentParentUserId:this.$store.state.articleDetail.author,
            commentParentUserNick: this.$store.state.articleDetail.authorNick,
            commentedCount:0
          }
        await this.axios.post(url, param)
          .then(response => {
            res = response.data;
          })
        if (res.success){
          param['createTime'] = new Date().getTime();
          this.commentList.unshift(param);
          this.content = "";
//          window.location.reload();
          let instance = Toast({message: '评论成功', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);

        }else{
          let instance = Toast({message: '网络链接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }

      },

      async upvote(){
        let url = '/v1/upvote'
        let param={
          userId: this.$store.state.userInfo.userId,
          articleId:  this.$store.state.articleDetail.id
        }
        let res
        if (!  this.$store.state.articleDetail.upvote){
          await this.axios.post(url, param)
            .then(response => {
              res = response.data;
            })
          if (res.success){
            this.$store.state.articleDetail.upvoteCount ++;
            this.UPDATE_UPVOTE();
            let instance = Toast({message: '点赞成功', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }else{
            let instance = Toast({message: '网络连接失败', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }
        }else{
          let instance = Toast({message: '您已点赞', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      },

      async like(){
        let url = '/v1/like'
        let param={
          userId: this.$store.state.userInfo.userId,
          articleId:  this.$store.state.articleDetail.id
        }
        let res
        if ( this.$store.state.articleDetail.like){
          await this.axios.put(url, param)
            .then(response => {
              res = response.data;
            })
          if (res.success){
            this.$store.state.articleDetail.likeCount --;
            this.UPDATE_LIKE();

            let instance = Toast({message: '取消收藏', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }else {
            let instance = Toast({message: '网络连接失败', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }
        }else{
          await this.axios.post(url, param)
            .then(response => {
              res = response.data;
            })
          if (res.success){
            this.$store.state.articleDetail.likeCount ++;
            this.UPDATE_LIKE();
            let instance = Toast({message: '收藏成功', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }else{
            let instance = Toast({message: '网络连接失败', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }
        }

      },
      autoResize() {
        let minRows = 1;
        let maxRows = 6;
        let t = document.getElementById("content_input");
        if (t.scrollTop == 0) t.scrollTop = 1;
        while (t.scrollTop == 0) {
          if (t.rows > minRows)
            t.rows--;
          else
            break;
          t.scrollTop = 1;
          if (t.rows < maxRows)
            t.style.overflowY = "hidden";
          if (t.scrollTop > 0) {
            t.rows++;
            break;
          }
        }
        while (t.scrollTop > 0) {
          if (t.rows < maxRows) {
            t.rows++;
            if (t.scrollTop == 0) t.scrollTop = 1;
          }
          else {
            t.style.overflowY = "auto";
            break;
          }
        }
      },

    },


  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
  .ivu-input{
    resize: none;
    font-size: 0.6rem;
    height: 0.6rem;
  }
  .mint-toast-text{
    font-size: 0.6rem;
  }
  .toast{
    min-width: 20%;
    width: 20%;
    span{
      color: #FFFFFF;
    }
  }

</style>
<style lang="scss" scoped>
  @import '../../style/mixin';

  .bottom_nav{
    background-color: #fff;
    position: fixed;
    z-index: 100;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    box-shadow: 0 -0.026667rem 0.053333rem rgba(0,0,0,.1);

    .content{
      width: 16rem;
      display: flex;
      font-size: 0.6rem;

      #content_input{
        background:transparent;
        overflow-y:hidden;
        resize:none;
        flex: 10;
        font-size: 0.6rem;
        border: solid 1px #33CCFF;
        text-indent: 0.5rem;
      }
      .btn{
        flex: 2;
        background-color: #33CCFF;
        color: #FFFFFF;
        font-weight: bold;

      }
    }
  }

  .my_header{
    background-color: #33CCFF;
    height: 1.5rem;
    padding-top: 0.2rem;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;

    .left{
      margin-left: 0.5rem;
      .icon_style{
        font-size: 0.6rem;
        font-weight: bold;
      }
      .back{
        background-color: transparent;
        font-size: 0.65rem;
        margin: 0;
      }
    }
  }

  .center{
    padding-top: 1.5rem;
    overflow: hidden;
    .center_header{
      @include wh(100%, 3rem);
      border-bottom: solid 1px #e3e8ee;
      display: flex;

      .center_header_left{
        display: inline-block;
        margin: 0.1rem 0.5rem;

        .avatar{
          @include wh(2.2rem, 2.2rem);
          @include borderRadius(1.1rem);
        }
      }

      .center_header_center{
        flex-direction: column;
        align-items: center;
        display: inline-block;
        margin: auto 0.2rem;
        .nick{
          margin: auto 0;
          font-size: 0.4rem;
          font-weight: bold;
        }
        .datetime{
          margin: auto 0;
          font-size: 0.3rem;
          font-weight: bold;
        }

      }

      .btn{
        width: 3rem;
        height: 0.8rem;
        background-color: #33CCFF;
        color: #FFFFFF;
        @include borderRadius(1.5rem);
        position: absolute;
        right: 1rem;
        margin-top: 0.2rem;

      }
    }
  }

  /* 单个节点尾部  开始*/
  .btn_nav{
    border-top: solid 1px #e3e8ee;
    padding-left: 0.5rem;
    display: flex;

    .btn_nav_item{
      flex: 1;
      display: flex;
      text-align: center;
      flex-direction: column;
      align-items: center;

      .icon_style{
        display: inline-block;
        font-size: 0.6rem;
      }


      .icon_style_active{
        color: #33CCFF;
      }

      .is_selected{
        color: #33CCFF;
      }
    }

  }

  .post_list_ul{
    padding-bottom: 2rem;

    .post_list_li{
      border: solid 1px #d7dde4;
      @include borderRadius(0.1rem);
      border-bottom: solid 10px #eaeaea;


      /*单个文章节点头部 开始*/
      .li_header{
        @include wh(100%, 1.6rem);
        border-bottom: solid 1px #e3e8ee;
        display: flex;

        .li_header_left{
          display: inline-block;
          margin: 0rem 0.5rem;

          .avatar{
            @include wh(1.3rem, 1.3rem);
            @include borderRadius(0.65rem);
            margin-top: 0.15rem;
          }
        }

        .li_header_center{
          flex-direction: column;
          align-items: center;
          display: inline-block;
          margin: auto 0.2rem;
          .nick{
            margin: auto 0;
            font-size: 0.4rem;
            font-weight: bold;
          }

        }

        .li_header_right{
          flex-direction: column;
          align-items: center;
          display: inline-block;
          margin: auto 0.2rem;

          .datetime{
            margin: auto 0;
            font-size: 0.3rem;
            font-weight: bold;
          }
        }

        .btn{
          width: 3rem;
          height: 0.8rem;
          background-color: #33CCFF;
          color: #FFFFFF;
          @include borderRadius(1.5rem);
          position: absolute;
          right: 1rem;
          margin-top: 0.35rem;
          font-size: 0.4rem;
        }
      }


      /* 单个节点中部，内容部分  开始*/
      .li_center{
        padding: 0.2rem 0.5rem;

        .li_center_container{
          background-color: #FFFFFF;
          padding: 0.3rem;

          .container{
            p{
              margin-left: 0.5rem;
              width:100%;/*要显示文字的宽度*/
              word-break: break-all;
              display: -webkit-box;
              -webkit-line-clamp: 6;  /*限制在一个块元素显示的文本的行数*/
              -webkit-box-orient: vertical;
              overflow: hidden;
            }

          }

        }
      }
    }
  }


</style>
